<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="20" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入名称或者用户编号搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <date-range-picker v-model="query.createTime" class="date-item" unlink-panels />
            <el-select
              v-model="query.enabled"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <el-select
              v-if="dict && dict.user_type"
              v-model="query.userType"
              clearable
              size="small"
              placeholder="用户类型"
              class="filter-item"
              style="width: 100px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.user_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-if="dict && dict.user_level"
              v-model="query.userLevel"
              clearable
              size="small"
              placeholder="会员等级"
              class="filter-item"
              style="width: 100px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.user_level"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="query.roleId"
              clearable
              size="small"
              placeholder="角色"
              class="filter-item"
              style="width: 100px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in roles"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" @keydown.native="keydown($event)" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model.number="form.phone" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="form.nickName" @keydown.native="keydown($event)" />
            </el-form-item>
            <el-form-item label="备注" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.gender" style="width: 178px">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.enabled" :disabled="form.id === user.id">
                <el-radio
                  v-for="item in dict.user_status"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-bottom: 0;" label="角色" prop="role">
              <el-select
                v-model="form.role.id"
                style="width: 437px"
                placeholder="请选择"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roles"
                  :key="item.name"
                  :disabled="level !== 1 && item.level <= level"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.role.id === 3" label="类型">
              <el-radio-group v-model="form.userType" style="width: 178px">
                <el-radio v-for="item in dict.user_type" :key="item.id" style="margin-right: 5px;" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.role.id === 3" label="等级">
              <el-radio-group v-model="form.userLevel">
                <el-radio
                  v-for="item in dict.user_level"
                  :key="item.id"
                  style="margin-right: 5px;"
                  :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.role.id === 3 && `${form.userLevel}` === '1'" label="VIP时间">
              <date-range-picker v-model="form.vipTime" class="date-item" unlink-panels />
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <el-dialog append-to-body :visible.sync="keywordDialog" :title="'个人配置管理'" width="700px">
          <div>
            <div>
              <el-form ref="form" :model="userParams" style="height: 500px;overflow: scroll;" size="small" label-width="130px">
                <el-card class="box-card" shadow="never">
                  <div slot="header" class="clearfix">
                    <span class="role-span">普通会员(默认值为系统参数)</span>
                  </div>

                  <el-card class="box-card" shadow="never" style="margin-top: 15px;">
                    <div slot="header" class="clearfix">
                      <span class="role-span">分享文章分成</span>
                    </div>
                    <el-form-item label="分享者" prop="memberShareArticleIncomeRatio">
                      <el-input v-model="userParams.memberShareArticleIncomeRatio" style="width: 130px" />
                      <span>%</span>
                    </el-form-item>
                    <el-form-item label="购买者上级" prop="memberArticleBuyParentIncomeRatio">
                      <el-input v-model="userParams.memberArticleBuyParentIncomeRatio" style="width: 130px" />
                      <span>%</span>
                    </el-form-item>
                  </el-card>
                  <el-card class="box-card" shadow="never" style="margin-top: 15px;">
                    <div slot="header" class="clearfix">
                      <span class="role-span">咨询合作分成</span>
                    </div>
                    <el-form-item label="购买者上级" prop="memberQueryBuyParentIncomeRatio">
                      <el-input v-model="userParams.memberQueryBuyParentIncomeRatio" style="width: 130px" />
                      <span>%</span>
                    </el-form-item>
                  </el-card>
                  <el-form-item label="推荐VIP分成" prop="memberVIPBuyParentIncomeRatio">
                    <el-input v-model="userParams.memberVIPBuyParentIncomeRatio" style="width: 130px" />
                    <span>%</span>
                  </el-form-item>
                </el-card>
              </el-form>
            </div>
            <div style="display:flex; flex-direction: row; align-items:center;">
              <el-button :loading="saveKeywordLoading" style="margin-top: 15px;margin-left: 5px;" type="primary" @click="saveUserParams">保存</el-button>
            </div>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名">
            <template slot-scope="scope">
              <a style="color: #00a0e9;" @click="getBuyInfo(scope.row.id)">{{ scope.row.username }}</a>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="nickName" label="昵称">
            <template slot-scope="scope">
              <a style="color: #00a0e9;">{{ scope.row.nickName }}</a>
            </template>
          </el-table-column>
          <el-table-column width="50" prop="id" label="ID">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column width="100" prop="id" label="备注">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户类型" align="center" prop="userType">
            <template slot-scope="scope">
              <span>{{ (dict.user_type.find(v=>(v.value) === `${scope.row.userType || 0}`) || {}).label }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户等级" align="center" prop="userLevel">
            <template slot-scope="scope">
              <span>{{ (dict.user_level.find(v=>(v.value) === `${scope.row.userLevel || 0}`)|| {}).label }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column prop="gender" label="性别" />-->
          <!--          <el-table-column :show-overflow-tooltip="true" prop="phone" width="100" label="电话" />-->
          <!--          <el-table-column :show-overflow-tooltip="true" width="135" prop="email" label="邮箱" />-->
          <el-table-column label="角色" align="center" prop="role">
            <template slot-scope="scope">
              <span>{{ scope.row.role.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="parentUser" align="center" label="上级">
            <template slot-scope="scope">
              <div>{{ scope.row.parentUser ? scope.row.parentUser.username: '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="childrenUserCount" label="下级数量">
            <template slot-scope="scope">
              <a style="color: #00a0e9;" @click="getChildren(scope.row.id, scope.row.username)">{{ scope.row.childrenUserCount }}</a>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createTime" width="135" label="创建日期" />
          <el-table-column
            v-if="checkPer(['admin','user:edit','user:del'])"
            label="操作"
            width="175"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
              >
                <el-button slot="left" size="mini" type="primary" icon="el-icon-plus" @click="updateParams(scope.row)" />
              </udOperation>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUser from '@/api/system/user'
import { getAll, getLevel } from '@/api/system/role'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudCommission from '@/api/system/commission'
import DateRangePicker from '@/components/DateRangePicker'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
const defaultForm = { id: null, username: null, nickName: null, vipTime: [], gender: '男', userType: '0', userLevel: '0', email: null, enabled: 'true', role: { id: 3 }, jobs: [], dept: { id: null }, phone: null }
export default {
  name: 'User',
  components: { crudOperation, rrOperation, udOperation, pagination, DateRangePicker },
  cruds() {
    return CRUD({ title: '用户', url: 'api/users', crudMethod: { ...crudUser }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status', 'user_type', 'user_level'],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      keywordDialog: false,
      userParams: {},
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      jobDatas: [], roleData: null, // 多选时使用
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.crud.msg.add = '新增成功，默认密码：123456'
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
    this.getRoles()
  },
  methods: {
    getChildren(id, username) {
      this.$router.push({
        path: '/user/children/' + id,
        query: { username }
      })
    },
    // 禁止输入空格
    keydown(e) {
      if (e.keyCode === 32) {
        e.returnValue = false
      }
    },
    updateParams(row) {
      this.selecUser = row
      if (row.systemParams) {
        this.userParams = JSON.parse(row.systemParams)
        this.userParams.username = row.username
        this.keywordDialog = true
      } else {
        crudCommission.getSystemParams().then(value => {
          this.userParams = value
          this.userParams.username = row.username
          this.keywordDialog = true
        })
      }
    },
    saveUserParams() {
      crudUser.updateUserParams({ username: this.userParams.username, systemParams: JSON.stringify(this.userParams) }).then(() => {
        this.selecUser.systemParams = JSON.stringify(this.userParams)
        this.userParams = {}
        this.keywordDialog = false
        this.$message.success('保存成功')
        this.selecUser = null
      })
    },
    getBuyInfo(id) {
      this.$router.push('/system/purchase?userId=' + id)
    },
    changeRole(value) {
      this.crud.form.role.id = value
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      this.getRoleLevel()
      form.enabled = form.enabled.toString()
      form.userType = form.userType.toString()
      form.userLevel = form.userLevel.toString()
      if (form.startTime && form.endTime) {
        form.vipTime = [form.startTime, form.endTime]
      } else {
        form.vipTime = []
      }
      // form.role.id = form.roleId
      console.log(form)
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      // this.roleData = null
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // this.roleData = null
      form.vipTime = []
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (`${crud.form.userLevel}` === '1' && crud.form.vipTime && crud.form.vipTime.length === 2) {
        crud.form.startTime = crud.form.vipTime[0]
        crud.form.endTime = crud.form.vipTime[1]
      } else {
        crud.form.startTime = undefined
        crud.form.endTime = undefined
      }
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudUser.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => { })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => { })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
  ::v-deep .box-card {
    margin-bottom: 5px;
    span {
      margin-right: 28px;
    }
    .el-icon-refresh {
      margin-right: 10px;
      float: right;
      cursor:pointer;
    }
  }

</style>
